package com.blindBox.back.config;

import com.blindBox.back.annotation.JwtToken;
import com.blindBox.back.commonResult.MsgBackToFront;
import com.blindBox.back.utils.JsonUtils;
import com.blindBox.back.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtTokenInterceptor extends HandlerInterceptorAdapter {
    //JACKSON
   private final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if(true)
        return true;

        JwtToken annotation;
        //拦截到的方法
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(JwtToken.class);
        } else {
            return true;
        }
        // 如果没有该注解，直接放行
        if (annotation == null) {
            return true;
        }

        System.out.println("=====================");
        System.out.println("拦截到的方法为: ");
        System.out.println(((HandlerMethod) handler).getMethod().getName());
        System.out.println("======================");
           //验证token
            MsgBackToFront res = JwtUtils.verity();
            if (res.getStatus().equals(MsgBackToFront.HANDLE_SUCCESS))
            {
                return true;
            }
        // 验证不通过，返回200，表示用户未登录
        //返回数据给前端,告诉验证结果失败
        JsonUtils.handleJsonDataBackToFront(200,MsgBackToFront.TOKEN_ERROR,null);
        return false;
    }

}
